<template>
  <div class="user_info infoBox appCon page_pos_style" :style="{ top: `${phoneStatusBarHeight}`}" style="padding:unset;">
    <!-- 顶部盒子 -->
    <!-- <van-nav-bar title="个人信息" fixed placeholder :border="false"> -->
      <!-- 顶部返回按钮 -->
      <!-- <template #left>
        <van-icon
          name="arrow-left"
          size="18"
          @click="$router.push({ name: 'PersonalCenter' })"
        />
      </template>
    </van-nav-bar>  -->
    
    <navbar :title="title"></navbar>
    <div>
      
    <!-- this is SetInfopage -->
    <van-cell center icon="user-o" title="头像" is-link>
      <!-- :to="{ name: 'EditName' }" -->
      <template #right-icon>
        <div class="flex-box">
          <van-uploader
            v-model="fileList"
            :after-read="headerImageChange"
            :deletable="false"
            :preview-image="false"
          >
            <van-image
              style="width: 2.8rem; height: 2.8rem"
              :src="imPicUrlNew"
            />
          </van-uploader>
          <van-icon name="arrow"></van-icon>
        </div>
      </template>
    </van-cell>
    <van-cell
      icon="friends-o"
      title="用户名"
      :to="{ name: 'EditName', query: { ty: 'name', name: name } }"
      is-link
      :value="infoList.personName"
    />
    <van-cell
      icon="phone-o"
      title="手机号码/账号"
      :to="{
        name: 'LookMobile',
        query: { uid: '1', mobile: infoList.mobile },
      }"
      is-link
      :value="infoList.mobile"
    />
    <div id="testdiv"  v-show="openid == '' || openid == null  ">
      <van-cell
          icon="chat-o"
          title="微信"
          is-link
          :value="'未绑定'"

      />
    </div>
    <div v-show="openid !=null && openid !='' " >
    <van-cell
      icon="chat-o"
      title="微信"
      is-link
      :value="infoList.vxName"
      @click="bindingWeChat"
    />
    </div>

    <van-cell
      icon="smile-comment-o"
      title="备注"
      is-link
      :to="{ name: 'EditName', query: { ty: 'remark', remark: remark } }"
      :value="remark"
    >
      <!-- <template #right-icon>
	  <div class="flex-box" >
	  		 <input clear v-model="info.remark"></input>
			 <van-icon name="arrow" />
	    </div>
	</template> -->
    </van-cell>
    <div class="loading_style" v-show="isLoading">
      <van-loading type="spinner" size='50px' color="#000000" :vertical='true'>正在更换头像...</van-loading>
    </div>
    </div>
  </div>
</template>

<script>
import { Dialog, Toast, Loading  } from "vant";
import { getUserInfoMyGetInfoC, getUpdataImPicUrl,getInfoMyUpdataVX } from "./api";
import upload from "@/common/upload.js";

export default {
  name: "SetInfo",
  data() {
    return {
        // header栏 => 标题
        title:"个人信息",

      // 用户信息
      infoList: {},
      // 用户头像
      imPicUrlNew: "",
      // 备注信息
      remark: "",
      name:'',
      // 头像
      fileList: [],
      // 用户id
      userId:'',
      // 获取屏幕状态栏高度
      phoneStatusBarHeight:'',
      isLoading:false,
      openid:''
    };
  },
  methods: {
    // 初始化用户数据
    async initUserInfoMyGetInfoC() {
      const  data  = await getUserInfoMyGetInfoC();
      if (data.code !== 0) return Toast(data.msg)
      let res = data.data
      this.infoList = res;
      this.mobile = res.mobile
      this.openid = res.openid
      console.log('%c [ this.openid ]-133', 'font-size:13px; background:pink; color:#bf2c9f;', this.openid)
      localStorage.setItem('mobile',res.mobile)
      localStorage.setItem('openid',res.openid)
      // this.imPicUrlNew = res.vxHeadUrl !== '' ? res.vxHeadUrl : res.infoCUser !== null ? res.infoCUser.imPicUrl : '';

      if (res.infoCUser !== null && res.infoCUser.imPicUrl !== '') {
        this.imPicUrlNew = res.infoCUser.imPicUrl
      }else if(res.vxHeadUrl !== '' || res.infoCUser == null || res.infoCUser.imPicUrl == '') {
        this.imPicUrlNew = res.vxHeadUrl
      }else{
        this.imPicUrlNew = ''
      }


      // this.fileList.push({ url: res.infoCUser.imPicUrl });
      this.remark = res.infoCUser !== null ? res.infoCUser.remark : '';
      this.name = res.personName
      this.userId = res.userId
    },
    // 点击微信
    bindingWeChat() {
      // if ( this.openid == '' ||  this.openid == null ) return
      Dialog.confirm({
        title: this.openid == "" ? "未绑定" : this.infoList.vxName,
        // title: this.infoList.vxName == "" ? "未绑定" : this.infoList.vxName,
        message:
          this.openid == "" ? "是否进行微信绑定" : "是否进行微信解绑",
          // this.infoList.vxName == "" ? "是否进行微信绑定" : "是否进行微信解绑",
      })
        .then(async () => {
          /* let appid = "wx905022c47889bf6b"; //换成自己的appid
          let uri = encodeURIComponent("http://192.168.1.38:8080/#/userInfo"); //link是需要登录的页面
          let authURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`; //这里使用的是非静默授权
          window.location.href = authURL; */
          console.log("[ 下一步操作 ]");
          let params = {
            type:0,
            userId:this.userId
          }
          const data = await getInfoMyUpdataVX(params)
          console.log('%c [ data ]', 'font-size:13px; background:pink; color:#bf2c9f;', data)
          if (data.code !== []) {
            Toast("解绑成功")
            this.infoList.vxName = '未绑定'
            this.initUserInfoMyGetInfoC()
          }else{
            Toast(data.msg)
          }

        })
        .catch(() => {
          // on cancel
          console.log("[ 取消操作 ]");
        });
    },
    // 上传头像
    headerImageChange(file) {
      console.log('%c [ file ]-171', 'font-size:13px; background:pink; color:#bf2c9f;', file)
      this.isLoading = true
      let formData = new FormData();
      formData.append("file", file.file);
      upload(
        (list) => {
          this.initUpdataImPicUrl({ imPicUrl: list.length ? list[0].url : '' })
        },
        [formData]
      );
    },
    // 上传头像
    async initUpdataImPicUrl(params) {
      const { data } = await getUpdataImPicUrl(params);
      Toast("头像修改成功!");
      this.isLoading = false
      // 初始化用户数据
      this.initUserInfoMyGetInfoC();
    },
    // 获取路由链接上拼接的token值
    getTokenInUrl(){
      var url = window.location.href;
      if (url.indexOf("token") > 0) {
        let getTokenParams = window.location.href.split("token=")[1];
        getTokenParams=getTokenParams.split("&")[0];
        if (getTokenParams.length >= 32) {
          getTokenParams = getTokenParams.substr(0, 32);
          console.log('%c [ getTokenParams ]', 'font-size:13px; background:pink; color:#bf2c9f;', getTokenParams)
          sessionStorage.setItem("token", getTokenParams);
        }
      }
    }
  },
    /* watch: {
      phoneStatusBarHeight(val, oldVal) {
      Toast("phoneStatusBarHeight = " + val + " , oldValue = " + oldVal)
      }
    }, */
  created() {
      // 获取屏幕状态栏高度
      if (window.phoneStatusBarHeight !== null || window.phoneStatusBarHeight !== '' || window.phoneStatusBarHeight !== undefined) {
        this.phoneStatusBarHeight = window.phoneStatusBarHeight
      }
      let localHeight = localStorage.getItem('phoneStatusBarHeight')
      if (localHeight !== null || localHeight !== '' || localHeight !== undefined) {
        this.phoneStatusBarHeight = localHeight
      }
    // 修改页面标题
    document.title = "个人信息"
    // 初始化用户数据
    this.initUserInfoMyGetInfoC();
    // 获取token值
    this.getTokenInUrl()
  },
  activated() {
    // 初始化用户数据
    this.initUserInfoMyGetInfoC();
  },
  mounted() {
    const conf = require('../../utils/conf')
    const baseURL = conf.baseURL
    // h5与uniapp的交互 => 点击绑定微信
    if (this.openid == '' || this.openid == null ) {
        document.addEventListener('UniAppJSBridgeReady',function(){
          document.getElementById('testdiv').addEventListener('click',function(){
            uni.postMessage({
              data:{
                type: 3, // 0 => 退出  ||  1 => 分享
                phone: localStorage.getItem('mobile'),
                returnUrl:`${baseURL}userInfo`
              }
            })
            console.log('[ localStorage.getItem ]', localStorage.getItem('mobile'))
            console.log('%c [ url ]-264', 'font-size:13px; background:pink; color:#bf2c9f;', `${baseURL}userInfo`)
        })
      })
    }
  },
};
</script>

<style lang="less" scoped>
.user_info{
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  .van-cell{
    .van-cell__title {
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      // height: 100px;
      width: 100%;
    }
    .van-cell__value {
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      // height: 100px;
      width: 100%;
    }
    .van-icon{
      font-size: 18px;
    }
  }
}
.loading_style{
  position: fixed;
  top: 40vh;
  bottom: 60vh;
  left: 50vw;
  right: 50vw;
}
</style>
